<template>
  <el-dialog :visible="isShowDialog" :destroy-on-close="true" @close="btnCancel">
    <el-form ref="clientForm" label-width="68px">
      <el-form-item label="经纪">
        <el-select v-model="formData.agent">
          <el-option
            v-for="item in agentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="微信">
        <el-input v-model="formData.wechat" />
      </el-form-item>
      <el-form-item label="详情">
        <el-input v-model="formData.desc" />
      </el-form-item>
      <el-form-item>
        <ImageUpload ref="upload" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      <el-button size="small" @click="btnCancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addClient, getClientDetail, editClient } from '@/api/client'
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    agentList: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      formData: {
        agent: '',
        image: '',
        name: '',
        phone: '',
        email: '',
        wechat: '',
        desc: ''
      }
    }
  },
  methods: {
    async btnOK() {
      if (!this.$refs.upload.fileList[0]) return this.$message.error('请先上传图片')
      if (this.$refs.upload.fileList[0].status !== 'success') return this.$message.error('请等待上传完毕')

      if (this.formData.id) {
        // 编辑
        await editClient({
          ...this.formData,
          image: this.$refs.upload.fileList[0].url
        })
      } else {
        // 新增
        await addClient({
          ...this.formData,
          image: this.$refs.upload.fileList[0].url
        })
      }

      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.$emit('update:isShowDialog', false)
      // 更新页面
      this.$emit('reloadPage')
    },
    btnCancel() {
      // 清空报错
      this.$refs.clientForm.resetFields()
      // 清空数据
      this.formData = {
        agent: '',
        image: '',
        name: '',
        phone: '',
        email: '',
        wechat: '',
        desc: ''
      }
      this.$refs.upload.fileList = []
      // 关闭弹窗
      this.$emit('update:isShowDialog', false)
    },
    async getClientDetail(id) {
      this.formData = await getClientDetail(id)
      this.$refs.upload.fileList = [{ url: this.formData.image }]
    }
  }
}
</script>

<style>

</style>
